from myapp import db
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash

user_organization_table = db.Table('sys_user_organization', db.Model.metadata
                                   , db.Column('user_id', db.String, db.ForeignKey('sys_user.id'))
                                   , db.Column('organization_id', db.String, db.ForeignKey('sys_organization.id')))

user_role_table = db.Table('sys_user_role', db.Model.metadata
                           , db.Column('user_id', db.String, db.ForeignKey('sys_user.id'))
                           , db.Column('role_id', db.String, db.ForeignKey('sys_role.id')))

class User(db.Model):
    __tablename__ = 'sys_user'
    id = db.Column(db.String(36), primary_key=True)
    create_time = db.Column(db.DateTime, index=True, default=datetime.now)
    update_time = db.Column(db.DateTime, index=True, default=datetime.now)
    login_name = db.Column(db.String(100), unique=True, index=True)
    pwd = db.Column(db.String(256))
    name = db.Column(db.String(100))
    sex = db.Column(db.String(1))
    age = db.Column(db.Integer)
    photo = db.Column(db.String(200))
    employ_date = db.Column(db.DATETIME, default=datetime.now)
    email = db.Column(db.String(50))
    phone_number = db.Column(db.String(11))
    status = db.Column(db.String(10))
    description = db.Column(db.String(255))
    organizations = db.relationship('Organization',
                                    secondary=user_organization_table,
                                    backref=db.backref('users', lazy='dynamic'),)

    roles = db.relationship('Role',
                            secondary=user_role_table,
                            backref=db.backref('users', lazy='dynamic'),
                            lazy="dynamic")

    def __repr__(self):
        return '<User %r>\n' % (self.name)

    def get_id(self):
        return str(self.id)

    def set_password(self, password):
        self.pwd = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.pwd, password)

    def have_permission(self, url):
        permissions = []
        for role in self.roles:
            permissions.extend([resource for resource in role.resources])

        if filter(lambda x: x.url == url, permissions):
            return True

        permissions = []
        for organization in self.organizations:
            permissions.extend([resource for resource in organization.resources])

        return filter(lambda x: x.name == url, permissions)

    def to_json(self):
        json = {
            'userId': self.id,
            'createTime': self.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'updateTime': self.update_time.strftime('%Y-%m-%d %H:%M:%S'),
            'username': self.login_name,
            'nickname': self.name,
            'sex': self.sex,
            'age': self.age,
            "status": self.status,
            'photo': self.photo,
            'email': self.email,
            'phoneNumber': self.phone_number,
            'description': self.description,
            'employdate': self.employ_date.strftime('%Y-%m-%d %H:%M:%S')
        }

        if len(self.organizations) > 0:
            json['dept']  = self.organizations[0].to_json()
            json['deptId'] = self.organizations[0].id

        if len(self.roles.all()) > 0:
            json['roles'] = [role.to_json() for role in self.roles.all()]

        return json         